﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using System.IO;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.Wiki.Activities
{



    class SubjectUIActivity : WebActivity
    {
        public static void Search(UISection ui, Subject[] subjects, String model, String cmd, bool isblock, bool isApp, Uri uri)
        {
            var subs = new List<Subject>();
            var cateids = new List<ulong>();
            var ids = new List<ulong>();
            var itemIds = new List<ulong>();

            Utility.Each(subjects, dr =>
            {
                subs.Add(dr);
                if (dr.project_id.HasValue)
                    cateids.Add(dr.project_id ?? 0);// Guid.Empty);
                ids.Add(dr.Id.Value);
                if (dr.project_item_id.HasValue)
                    itemIds.Add(dr.project_item_id.Value);
            });
            var projects = new List<Project>();
            var pitems = new List<ProjectItem>();


            if (itemIds.Count > 0)
            {
                pitems.AddRange(DataFactory.Instance().ProjectItem(itemIds.ToArray()));
            }
            if (cateids.Count > 0)
            {
                projects.AddRange(DataFactory.Instance().Projects(cateids.ToArray()));
            }
            


            var items = ui;
            var webr = UMC.Web.WebResource.Instance();


            foreach (var sub in subs)
            {
                if (sub.Status == -2)
                {
                    continue;
                }
                
                int[] imageIndexs = Utility.BitIndex(sub.ImageIndexs ?? 0);
                var imgs = new List<String>();

                switch (imageIndexs.Length)
                {
                    case 0:
                        break;
                    case 2:
                    case 1:
                        if (isApp)
                        {
                            imgs.Add(webr.ImageResolve(uri, sub.Id, imageIndexs[0], (sub.IsPicture ?? false) ? "-1" : "-3", "_ts=" + sub.ImageIndexs));

                        }
                        else
                        {
                            imgs.Add(webr.ImageResolve(uri, sub.Id, imageIndexs[0], "-3", "_ts=" + sub.ImageIndexs));

                        }

                        break;
                    default:
                        for (var i = 0; i < 3; i++)
                        {
                            imgs.Add(webr.ImageResolve(uri, sub.Id, imageIndexs[i], "-3", "_ts=" + sub.ImageIndexs));
                        }
                        break;
                }
                var click = new Web.UIClick(model, cmd, sub.Id.ToString());
                var data = new UMC.Web.WebMeta().Put("title", sub.Title).Put("reply", (sub.Reply ?? 0).ToString()).Put("look", (sub.Look ?? 0).ToString());


                var cate = projects.Find(g => g.Id == sub.project_id);
                var pitem = pitems.Find(g => g.Id == sub.project_item_id);
                data.Put("pname", cate == null ? "草稿" : cate.Caption);
                var pUId = Utility.UInt64Parse(sub.user_id.Value);
                if (sub.project_id == pUId)
                {
                    data.Put("iname", "");
                }
                else
                {
                    data.Put("iname", pitem == null ? "" : pitem.Caption);
                }
                data.Put("time", Utility.GetDate(sub.ReleaseTime));
                if (cate != null && pitem != null)
                {
                    data.Put("spa", new WebMeta().Put("id", sub.Id).Put("path", String.Format("{0}/{1}/{2}", cate.Code, pitem.Code, sub.Code)));
                }
                else
                {
                    data.Put("sub-id", sub.Id.Value);

                }
                data.Put("desc", sub.Description);
                UICMS cell;
                switch (imgs.Count)
                {
                    case 0:
                        cell = new UICMS(click, data);
                        break;
                    default:

                        cell = (sub.IsPicture ?? false) ? new UICMS(click, data, imgs[0], isApp) : (imgs.Count > 2 ? new UICMS(click, data, imgs[0], imgs[1], imgs[2]) : new UICMS(click, data, imgs[0]));
                        break;
                }
                // cell.d
                cell.Formats.Put("left", "{pname} {iname} {time}");
                cell.Style.Name("licon", new UIStyle().Size(12).Font("wdk")).Name("ricon", new UIStyle().Size(12).Font("wdk"));
                cell.Style.Name("pname").Color(0x777);
                cell.Style.Name("iname").Color(0x777);
                if (isblock)
                {
                    cell.Close(new UIEventText().Icon('\uea0d', 0x999).Click(UIClick.Click(new UIClick(model, "TipOff", "Id", sub.Id.ToString(), "Type", "Block"))));

                }
                
                cell.Formats.Put("right", "\uF06E{1:licon} {look}   \uF0E6{1:ricon} {reply}");
                items.Add(cell);
            }

        }

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var search = new Subject();
            var webr = UMC.Web.WebResource.Instance();
            var form = request.SendValues ?? new UMC.Web.WebMeta();

            int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
            int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);

            search.project_id = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("project_id", r =>
            {
                var Project = form["Project"] as string;
                if (String.IsNullOrEmpty(Project) == false)
                {
                    var pid = UMC.Data.Utility.UInt64Parse(Project);

                    if (pid.HasValue == false)
                    {
                        var project = DataFactory.Instance().Project(Project);
                        if (project != null)
                        {
                            return this.DialogValue(project.Id.ToString());
                        }
                    }
                    else
                    {
                        return this.DialogValue(pid.ToString());
                    }
                }
                return this.DialogValue("none");
            }));

            // var pics = new List<UMC.Data.Entities.Picture>();

            search.Status = 1;

            var Keyword = (form["Keyword"] as string ?? String.Empty);

            if (String.IsNullOrEmpty(Keyword) == false)
            {
                search.Title = Keyword;
            }
            var ui = UISection.Create();
            var items = ui;
            if (start == 0)
            {
                if (String.IsNullOrEmpty(Keyword) == false)
                {
                    ui.Title = new UITitle(String.Format("搜索“{0}”资讯", Keyword));
                }
                else if (search.project_id.HasValue)
                {
                    if (ui.Length > 0)
                    {
                        items = ui.NewSection();
                    }
                }

            }
            int nextIndex;
            var subjects = DataFactory.Instance().Search(search, start, out nextIndex, limit);


            Search(items, subjects, request.Model, "UIData", String.IsNullOrEmpty(Keyword) && request.IsApp, request.IsApp, request.Url);

            ui.StartIndex = nextIndex;
            ui.IsNext = nextIndex > 0;
            if (start == 0 && ui.Length == 0)
            {
                if (search.project_id.HasValue)
                {
                    var desc = "还未有发布的项目资讯";
                    if (String.IsNullOrEmpty(Keyword) == false)
                    {
                        desc = "未搜索到相关项目内容";
                    }
                    ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", desc).Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                                        new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                }
                else
                {
                    var desc = "还未有发布的项目资讯";
                    if (String.IsNullOrEmpty(Keyword) == false)
                    {
                        desc = "未搜索到相关项目资讯";
                    }
                    ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", desc).Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                        new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                }
            }
            ui.SendTo(this.Context);
        }

    }
}